import time
import pytest
import allure
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException

@allure.feature("TP商城全流程自动化测试")
class TestTPShopFullFlow:
    @classmethod
    def setup_class(cls):
        cls.service = Service(r'F:\python 3.12\chromedriver.exe')
        cls.driver = webdriver.Chrome(service=cls.service)
        cls.driver.implicitly_wait(20)
        cls.driver.maximize_window()

    @classmethod
    def teardown_class(cls):
        input("按回车键关闭浏览器...")
        cls.driver.quit()

    @allure.story("用户登录流程")
    def test_user_login(self):
        with allure.step("1. 访问商城首页"):
            self.driver.get('https://hmshop-test.itheima.net/')
            time.sleep(3)
            allure.attach(self.driver.get_screenshot_as_png(), "首页截图", allure.attachment_type.PNG)

        with allure.step("2. 点击登录链接"):
            login_link = self.driver.find_element(By.CLASS_NAME, 'red')
            login_link.click()
            time.sleep(3)
            allure.attach(self.driver.get_screenshot_as_png(), "登录页截图", allure.attachment_type.PNG)

        with allure.step("3. 输入登录信息（手机号、密码、验证码）"):
            self.driver.find_element(By.ID, 'username').send_keys('13097860112')
            time.sleep(2)
            self.driver.find_element(By.ID, 'password').send_keys('123456')
            time.sleep(2)
            self.driver.find_element(By.ID, 'verify_code').send_keys('8888')
            time.sleep(2)
            allure.attach(self.driver.get_screenshot_as_png(), "登录信息输入截图", allure.attachment_type.PNG)

        with allure.step("4. 提交登录"):
            login_button = self.driver.find_element(By.CLASS_NAME, 'J-login-submit')
            login_button.click()
            time.sleep(5)
            allure.attach(self.driver.get_screenshot_as_png(), "登录后截图", allure.attachment_type.PNG)

    @allure.story("商品搜索与加入购物车流程")
    def test_search_and_add_cart(self):
        with allure.step("1. 搜索“华为”商品"):
            search_input = self.driver.find_element(By.ID, 'q')
            search_input.send_keys('华为')
            time.sleep(2)
            self.driver.find_element(By.CLASS_NAME, 'search_usercenter_btn').click()
            time.sleep(5)
            allure.attach(self.driver.get_screenshot_as_png(), "搜索结果页截图", allure.attachment_type.PNG)

        with allure.step("2. 搜索结果页加入购物车"):
            try:
                add_cart_btn1 = WebDriverWait(self.driver, 20).until(
                    EC.element_to_be_clickable((By.XPATH, '//a[contains(@onclick, "AjaxAddCart(13")]'))
                )
                add_cart_btn1.click()
                time.sleep(4)
                allure.attach(self.driver.get_screenshot_as_png(), "搜索页加入购物车后截图", allure.attachment_type.PNG)
            except TimeoutException:
                allure.attach(self.driver.get_screenshot_as_png(), "搜索页加入购物车失败截图", allure.attachment_type.PNG)
                pytest.fail("搜索结果页加入购物车按钮未找到")

        with allure.step("3. 商品详情页加入购物车"):
            try:
                join_cart_btn = WebDriverWait(self.driver, 20).until(
                    EC.element_to_be_clickable((By.ID, 'join_cart'))
                )
                join_cart_btn.click()
                time.sleep(5)
                allure.attach(self.driver.get_screenshot_as_png(), "详情页加入购物车后截图", allure.attachment_type.PNG)
            except TimeoutException:
                allure.attach(self.driver.get_screenshot_as_png(), "详情页加入购物车失败截图", allure.attachment_type.PNG)
                pytest.fail("详情页加入购物车按钮未找到")

        with allure.step("4. 处理加入购物车弹窗并跳转购物车"):
            try:
                # 等待弹窗外层容器
                popup_container = WebDriverWait(self.driver, 30).until(
                    EC.presence_of_element_located((By.CLASS_NAME, 'layui-layer-iframe'))
                )
                # 定位并切换到iframe
                cart_iframe = WebDriverWait(self.driver, 20).until(
                    EC.presence_of_element_located((By.XPATH, '//iframe[contains(@id, "layui-layer-iframe")]'))
                )
                self.driver.switch_to.frame(cart_iframe)
                # 点击“去购物车结算”
                go_cart_btn = WebDriverWait(self.driver, 20).until(
                    EC.element_to_be_clickable((By.XPATH, '//a[contains(@href, "/index.php/Home/Cart/index.html") and text()="去购物车结算"]'))
                )
                go_cart_btn.click()
                time.sleep(5)
                allure.attach(self.driver.get_screenshot_as_png(), "弹窗操作后截图", allure.attachment_type.PNG)
                # 切回主页面
                self.driver.switch_to.default_content()
            except TimeoutException:
                allure.attach(self.driver.get_screenshot_as_png(), "弹窗处理失败截图", allure.attachment_type.PNG)
                pytest.fail("加入购物车弹窗处理失败")

    @allure.story("购物车结算与订单提交流程")
    def test_checkout_and_submit_order(self):
        with allure.step("1. 购物车页面点击“去结算”"):
            try:
                checkout_btn = WebDriverWait(self.driver, 25).until(
                    EC.element_to_be_clickable((By.XPATH, '//a[contains(@class, "paytotal") and contains(@data-url, "/index.php/Home/Cart/cart2.html")]'))
                )
                checkout_btn.click()
                time.sleep(5)
                allure.attach(self.driver.get_screenshot_as_png(), "购物车去结算后截图", allure.attachment_type.PNG)
            except TimeoutException:
                allure.attach(self.driver.get_screenshot_as_png(), "购物车去结算失败截图", allure.attachment_type.PNG)
                pytest.fail("购物车去结算按钮未找到")

        with allure.step("2. 结算页面提交订单"):
            try:
                submit_order_btn = WebDriverWait(self.driver, 25).until(
                    EC.element_to_be_clickable((By.ID, 'submit_order'))
                )
                submit_order_btn.click()
                time.sleep(5)
                allure.attach(self.driver.get_screenshot_as_png(), "提交订单后截图", allure.attachment_type.PNG)
            except TimeoutException:
                allure.attach(self.driver.get_screenshot_as_png(), "提交订单失败截图", allure.attachment_type.PNG)
                pytest.fail("提交订单按钮未找到")

    @allure.story("支付确认流程")
    def test_confirm_payment(self):
        with allure.step("1. 点击“确认支付方式”完成支付"):
            try:
                confirm_pay_btn = WebDriverWait(self.driver, 20).until(
                    EC.element_to_be_clickable((By.XPATH, '//a[contains(@class, "button-confirm-payment") and text()="确认支付方式"]'))
                )
                confirm_pay_btn.click()
                time.sleep(5)
                allure.attach(self.driver.get_screenshot_as_png(), "确认支付后截图", allure.attachment_type.PNG)
            except TimeoutException:
                allure.attach(self.driver.get_screenshot_as_png(), "确认支付失败截图", allure.attachment_type.PNG)
                pytest.fail("确认支付方式按钮未找到")

        with allure.step("2. 全流程执行完成"):
            print("全流程自动化测试执行完毕，报告已生成")